Python

Set: 집합

자세한 항목은 Python 문서 참조: https://docs.python.org/2/library/sets.html#set-objects

  • 교집합: a & b
  • 합집합: a | b or a.union(b)
  • 차집합: a - b or a.difference(b)
  • 차집합의 대칭: a ^ b or a.symmetric_difference(b)
    • 차집합의 대칭은 (a | b) - (a & b)와 같다.

Date 와 Datetime

  • datetime을 date로 변환:

      from datetime import datetime
    
      datetime.now().date()
    
  • doy(day of year), date 상호 변환: "%j" format과 timetuple 사용

      from datetime import datetime
    
      year = 2015
      doy = 334
    
      datetime.strptime("{0}{1}".format(2015, 334), "%Y%j")
    
      # 반대로 date를 doy로 변환
      # 1. timetuple
      datetime.now().timetuple().tm_yday
    
      # 2. strftime의 %j format
      datetime.now().strftime("%j")
    

class 비교연산자

Python class 간에 ==, != 연사자를 이용해 비교를 해야하는 경우가 있다. python 에서는 class에 __eq__, __ne__ 매서드를 정의하여 사용하면 된다. set함수에서 동일한 class 인 경우 하나로 넣고 싶을때는 __hash__ 매서드를 정의해주자. 아래는 예제 코드다.

class Number(object):
    """Very basic"""
    def __init__(self, some_number):
        self.some_number = some_number

    def __eq__(self, other):
        """Override the default Equals behavior"""
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        return NotImplemented

    def __ne__(self, other):
        """Define a non-equality test"""
        if isinstance(other, self.__class__):
            return not self.__eq__(other)
        return NotImplemented

    def __hash__(self):
        """Override the default hash behavior (that returns the id or the object)"""
        return hash(tuple(sorted(self.__dict__.items())))


n1 = Number(1)
n2 = Number(1)

class NumberPlus(Number):
    pass

n3 = NumberPlus(1)
n4 = NumberPlus(4)

assert n1 == n2
assert n2 == n1
assert not n1 != n2
assert not n2 != n1

assert n1 == n3
assert n3 == n1
assert not n1 != n3
assert not n3 != n1

assert not n1 == n4
assert not n4 == n1
assert n1 != n4
assert n4 != n1

assert len(set([n1, n2, n3, ])) == 1
assert len(set([n1, n2, n3, n4])) == 2

참고:

shelve module 사용의 주의점

참고: http://stackoverflow.com/a/16231228

Shelve 패키지는 임시적인 Key:Value 값을 파일로 저장하기 위해서 주로 사용한다. 일시적인 데이터베이스로 사용한다는 것이다. 그런데 잘 사용하던 것이, 어떤 Linux 환경에서는 내가 원하는 특정 파일명으로 잘 저장해주는 반면, 어떤 경우는 'bak, dat, dir' 파일을 생성하는 경우가 있는 것을 발견했다.

더 암울했던 점은, 기존에 만들어 사용하던 shelve 파일이 'bak, dat, dir'을 생성하는 환경에서는 open 이 되지 않는다. 애러는 _bsddb 모듈을 import 할 수 없다는 것인데... 관련해서 좀 찾아봤다.

StackOverFlow에 그 해답이 있었다.

shelve 모듈은 anydbm 모듈로서 생성이 되는데, 이 anydbm은 4가지 다른 방식의 DBM 방식을 사용한다. 그리고 그 사용 순서는 아래 순서와 같다. 결국 우선순위 대로 해당 경우의 라이브러리를 back 단에서 사용한다는 것이다.

  1. dbhash (deprecated but still the first anydbm choice). This is a proxy for the bsddb module, .open() is really bsddb.hashopen()
  2. gdbm, Python module for the GNU DBM library, offering more functionality than the dbm module can offer when used with this same lbrary.
  3. dbm, a proxy module using either the ndbm, BSD DB and GNU DBM libraries (choosen when Python is compiled).
  4. dumbdbm, a pure-python implementation.

기존에 내가 사용하던 shelve 녀석은 dbhash(bsddb 모듈의 대리)을 사용하고 있었던 것이다.

그리고 대부분의 1,2,3 순위에 해당하지 않으면 dumbdbm(pure-python implementation)을 사용한다. 그리고 dumbdbm이 바로 'bak, dat, dir'을 생성하는 녀석이었다. (심지어 dbm은 'dir, pag, db' 파일로 생성한다)

결국 각기 다른 환경에서 shelve를 사용하는 경우 기존의 shelve db파일을 사용하지 못 할 수도 있다는 것이다. 이걸 알고나서 부터는 정말 꼭 중요한 데이터를 DB형식으로 저장하기 위해서는 shelve를 사용하지 않는 것이 바람직해 보인다.

(뿐만아니라 shelve는 동시 다발적으로 파일을 open 했을때 파일이 깨지기도 하는 문제가 있다. sqlite는 lock을 걸어서 한쪽에서만 쓰는 것을 허용하고 다른 쪽 요청을 수행한다)

results matching ""

    No results matching ""